﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace PrattParsing
{
    [DebuggerNonUserCode]
    public class ParseletMap<P>
    {
        P def;

        List<TokenMatch> matches;
        List<P> parselets;

        public ParseletMap(P defaultValue)
        {
            def = defaultValue;
            parselets = new List<P>();
            matches = new List<TokenMatch>();
        }
        public ParseletMap()
        {
            def = default(P);
            parselets = new List<P>();
            matches = new List<TokenMatch>();
        }

        public void set(TokenMatch match, P parselet)
        {
            int matchIndex = matches.IndexOf(match);
            if (matchIndex < 0)
            {
                matches.Add(match);
                parselets.Add(parselet);
            }
            else
            {
                parselets[matchIndex] = parselet;
            }
        }

        public P get(Token token)
        {
            P typeMatch = def;
            P textMatch = def;
            bool foundTextMatch = false;
            for (int i = 0; i < matches.Count; i++)
            {
                TokenMatch match = matches[i];
                if (match.Matches(token))
                {
                    if (match.matchType == TokenMatch.TEXT)
                    {
                        textMatch = parselets[i];
                        foundTextMatch = true;
                        break;
                    }
                    else
                    {
                        typeMatch = parselets[i];
                    }
                }
            }

            return foundTextMatch ? textMatch : typeMatch;
        }
    }
}
